#!/bin/bash
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/sys_check.sh"
# param 1: remote url
# param 2: local file path
download_with_resume() {
    local LOCAL_FILE="$1"
    local URL="$2"
    local MIN_SIZE=5242880  # 5MB (1024*1024*5)
    local ONE_MONTH_SECONDS=$((30 * 24 * 60 * 60))  # 30 days in seconds
    local NO_REVOKE_PARAM="--ssl-no-revoke"
    local CONTINUE_PARAM="-C -"
    echo "download $URL"
    if current_os_is_windows; then
        NO_REVOKE_PARAM="--ssl-no-revoke"
    fi

    if [ -f "$LOCAL_FILE" ]; then
        # file size
        local file_size
        # Get file modification time (in seconds)
        local file_mtime
        if [ -f /System/Library/CoreServices/SystemVersion.plist ]; then
            file_size=$(stat -f%z "$LOCAL_FILE")
            file_mtime=$(stat -f%m "$LOCAL_FILE")
        else
            file_size=$(stat -c%s "$LOCAL_FILE")
            file_mtime=$(stat -c%Y "$LOCAL_FILE")
        fi
          
        local current_time
        current_time=$(date +%s)

        local age=$((current_time - file_mtime))
        
        echo "current_time=$current_time"
        echo "file_mtime=$file_mtime"
        echo "age=$age"

        # Check if the file size is less than 5MB
        if [ $file_size -lt $MIN_SIZE ]; then
            echo "If the file size is less than 5MB, delete it and download it again."
            rm -f "$LOCAL_FILE"
            CONTINUE_PARAM=""
        # 检查文件是否超过1个月
        elif [ $age -gt $ONE_MONTH_SECONDS ]; then
            echo "If the file hasn't been updated for over 1 month, delete it and download it again."
            CONTINUE_PARAM=""
            rm -f "$LOCAL_FILE"
        else
            echo "The file exists and meets the conditions, attempting resumable transfer."
        fi
    else
        
        echo "The file does not exist, starting download."
        # curl -L -o "$LOCAL_FILE" "$URL"
    fi

    curl -L $CONTINUE_PARAM $NO_REVOKE_PARAM --retry 5 -o "$LOCAL_FILE" "$URL"

    curl_exit=$?
    if [ $curl_exit -eq 0 ]; then
        echo "Download completed: $LOCAL_FILE"
        return 0
    else
        echo "Download failed"
        return 1
    fi
}

# if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
#     if [ $# -ne 2 ]; then
#         echo "Usage: ${0##*/} <URL> <Local file path>" >&2
#         exit 1
#     fi
#     download_with_resume "$1" "$2"
# fi

